package edu.gatech.cs4400.spring2014.A8.control;

import edu.gatech.cs4400.spring2014.A8.model.WriteQuery;
import edu.gatech.cs4400.spring2014.A8.view.ApplicationWindow;
import edu.gatech.cs4400.spring2014.A8.view.RegistrationPanel;

/**
 * Controller for the registration process.
 * 
 * @author Stephen
 */
public class RegistrationController implements Controller {
	private RegistrationPanel.Feedback feedback;
	
	/**
	 * Constructor
	 */
	public RegistrationController() {
		feedback = null;
	}
	
	/**
	 * Display the registration form until the user registers a valid account
	 *  or hits cancel.
	 */
	public void run() {
		RegistrationPanel rp = new RegistrationPanel();
		ApplicationWindow.addView(rp, "RegistrationScreen");
		ApplicationWindow.setView("RegistrationScreen");
		
		while (true) {
			//block pending user input
			Waiter.waitFor(rp);
			feedback = rp.getFeedback();
			if (feedback == RegistrationPanel.Feedback.REGISTER) {
				RegistrationQuery rq = new RegistrationQuery(rp.getUsername(), rp.getPassword(), rp.getAccountType());
				if (rq.register()) {
					//if registration was successful, log in and direct the user to create a profile
					Session.setActiveAccount(rp.getUsername(), rp.getAccountType());
					if (rp.getAccountType().equals("patient")){
						(new PatientProfileController()).run(true);
					}
					else if (rp.getAccountType().equals("doctor")) {
						(new DoctorEditProfileController()).run(true);
					}					
					return;
				}
				else {
					//if registration was unsuccessful, tell the user and reset the form
					rp.reset();
					rp.setMessage(String.format("Username '%s' is already in use.", rp.getUsername()));
				}
			}
			else if (feedback == RegistrationPanel.Feedback.CANCEL) {
				//if user selects cancel, exit this process
				return;
			}
		}
	}
	
	/**
	 * Pass through the results of this operation
	 * @return
	 */
	public RegistrationPanel.Feedback getFeedback() {
		return feedback;
	}
	
	/**
	 * Query to insert the new user data into the database
	 * 
	 * @author Stephen
	 */
	private class RegistrationQuery extends WriteQuery {
		
		/**
		 * Build query 
		 * 
		 * @param username New username
		 * @param password Password
		 * @param accountType Account type
		 */
		public RegistrationQuery(String username, String password, String accountType) {
			sql = String.format("INSERT INTO Users VALUES('%s', '%s', '%s') ", username, password, accountType);
		}
		
		/**
		 * Execute query. 
		 * @return Success of registration
		 */
		public boolean register() {
			return execute();
		}
	}
}
